<!-- src/views/blog/index.vue -->
<template>
	<div class="overflow-hidden">
		<n-card class="h-full rounded-8px shadow-sm">
			<div class="flex-col h-full">
				<div class=" w-full  ">
					<!-- 搜索表单 -->
					<n-form inline :model="searchForm" label-placement="left">
						<n-form-item label="标题">
							<n-input v-model:value="searchForm.title" placeholder="请输入标题" clearable />
						</n-form-item>
						<n-form-item label="摘要">
							<n-input v-model:value="searchForm.summary" placeholder="请输入摘要" clearable />
						</n-form-item>
						<n-form-item label="类型">
							<n-select v-model:value="searchForm.type" :options="blogTypeOptions" clearable placeholder="请选择类型"
								style="width: 180px;" />
						</n-form-item>
						<n-form-item>
							<n-button type="primary" @click="handleSearch">搜索</n-button>
							<n-button @click="handleReset" style="margin-left: 10px;">重置</n-button>
						</n-form-item>
					</n-form>
					<!-- 操作按钮 -->
					<n-space>
						<n-button type="primary" @click="handleAdd">新增博客</n-button>
					</n-space>
				</div>
				<!-- 博客表格 -->
				<div class="h-full  flex">
					<n-data-table :scroll-x="1800" :columns="columns" :data="tableData" :loading="loading"
						:pagination="pagination" remote @update:page="handlePageChange" @update:page-size="handlePageSizeChange"
						flex-height class="flex-1"  :single-line="false" />
				</div>
			</div>
		</n-card>

		<!-- 博客编辑弹窗 -->
		<BlogEditModal v-model:show="showEditModal" :currentBlogId="currentBlogId" @save="handleSaveBlog"
			@close="handleCloseEditModal" />
	</div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, h } from 'vue';
import { NButton, NTag, NPopconfirm, useMessage } from 'naive-ui';
import { blogApi, type BlogListInput, type BlogListOutput, ArticleTypeLabels, ArticleType, ArticleStatus, ArticleStatusLabels } from '@/service/api/blog';
import type { DataTableColumns, PaginationProps } from 'naive-ui';
import BlogEditModal from './components/BlogEditModal.vue';

// 消息提示
const message = useMessage();

// 搜索表单数据
const searchForm = ref<BlogListInput>({
	pageIndex: 1,
	pageSize: 10,
	title: null,
	summary: null,
	type: undefined,
	keyword: null
});

// 表格数据
const tableData = ref<BlogListOutput[]>([]);
const loading = ref(false);
const total = ref(0);

// 编辑弹窗相关
const showEditModal = ref(false);
const currentBlogId = ref<number | undefined | null>(null);

// 分页配置
const pagination = computed<PaginationProps>(() => ({
	page: searchForm.value.pageIndex,
	pageSize: searchForm.value.pageSize,
	showSizePicker: true,
	pageSizes: [10, 20, 30, 50],
	itemCount: total.value,
	prefix({ itemCount }) {
		return `共有 ${itemCount} 条数据`;
	}
}));

// 博客类型选项（根据 ArticleType 枚举动态生成）
const blogTypeOptions = Object.entries(ArticleType)
	.filter(([, value]) => typeof value === 'number') // 确保 value 是 ArticleType 枚举值（数字）
	.map(([label, value]) => ({
		label: ArticleTypeLabels[value as ArticleType], // 使用标签映射作为显示文本
		value: value as ArticleType // 使用数字值作为选项值
	}));

// 表格列定义
const columns: DataTableColumns<BlogListOutput> = [
	{
		title: 'ID',
		key: 'id',
		width: 80
	},
	{
		title: '标题',
		key: 'title',
		width: 200,
		ellipsis: true
	},
	{
		title: '摘要',
		key: 'summary',
		width: 250,
		ellipsis: true
	},
	{
		title: '类型',
		key: 'type',
		width: 120, render: (row) => {
			if (row.type) {
				const tagTypes: Record<ArticleType, NaiveUI.ThemeColor> = {
					[ArticleType.Original]: "success",
					[ArticleType.Reprint]: "info",
				};
				return h(NTag, { type: tagTypes[row.type] }, { default: () => ArticleTypeLabels[row.type] });
			}
			else {
				return '-';
			}
		},
	},
	{
		title: '状态',
		key: 'status',
		width: 120, render: (row) => {
			if (row.type) {
				const tagTypes: Record<ArticleStatus, NaiveUI.ThemeColor> = {
					[ArticleStatus.Draft]: "success",
					[ArticleStatus.Published]: "info",
				};
				return h(NTag, { type: tagTypes[row.status] }, { default: () => ArticleStatusLabels[row.status] });
			}
			else {
				return '-';
			}
		},
	},
	{
		title: '浏览量',
		key: 'views',
		width: 100
	},
	{
		title: '点赞数',
		key: 'likes',
		width: 100
	},
	{
		title: '评论数',
		key: 'commentCount',
		width: 100
	},
	{
		title: '发布时间',
		key: 'publicationTime',
		width: 180,
		render(row) {
			return row.publicationTime ? new Date(row.publicationTime).toLocaleString() : '-';
		}
	},
	{
		title: '更新时间',
		key: 'updatedAt',
		width: 180,
		render(row) {
			return row.updatedAt ? new Date(row.updatedAt).toLocaleString() : '-';
		}
	},
	{
		title: '操作',
		key: 'actions',
		width: 250,
		fixed: 'right',
		render(row) {
			const actions = [
				h(
					NButton,
					{
						size: 'small',
						onClick: () => handleView(row)
					},
					{ default: () => '查看' }
				),
				h(
					NButton,
					{
						size: 'small',
						type: 'primary',
						style: 'margin-left: 10px;',
						onClick: () => handleEdit(row)
					},
					{ default: () => '编辑' }
				),
				h(
					NPopconfirm,
					{
						onPositiveClick: () => deleteBlog(row),
						negativeText: '取消',
						positiveText: '确认'
					},
					{
						trigger: () => h(
							NButton,
							{
								size: 'small',
								type: 'error',
								style: 'margin-left: 10px;'
							},
							{ default: () => '删除' }
						),
						default: () => '确定要删除这篇博客吗？'
					}
				)
			];

			// 只有当博客状态不是已发布时才显示发布按钮
			if (row.status !== ArticleStatus.Published) {
				actions.push(
					h(
						NButton,
						{
							size: 'small',
							type: 'success',
							style: 'margin-left: 10px;',
							onClick: () => published(row)
						},
						{ default: () => '发布' }
					)
				);
			}

			return h('div', actions);
		}
	}
];

// 获取博客列表数据
const fetchBlogList = async () => {
	loading.value = true;
	try {
		const result = await blogApi.GetBlogs(searchForm.value);
		if (result) {
			tableData.value = result.pageDatas || [];
			total.value = result.total || 0;
		} else {
			tableData.value = [];
			total.value = 0;
		}
	} catch (error) {
		message.error('获取博客列表失败');
		console.error(error);
	} finally {
		loading.value = false;
	}
};

// 处理搜索
const handleSearch = () => {
	searchForm.value.pageIndex = 1;
	fetchBlogList();
};

// 处理重置
const handleReset = () => {
	searchForm.value = {
		pageIndex: 1,
		pageSize: 10,
		title: null,
		summary: null,
		type: undefined
	};
	fetchBlogList();
};

// 处理分页变化
const handlePageChange = (page: number) => {
	searchForm.value.pageIndex = page;
	fetchBlogList();
};

// 处理页面大小变化
const handlePageSizeChange = (pageSize: number) => {
	searchForm.value.pageIndex = 1;
	searchForm.value.pageSize = pageSize;
	fetchBlogList();
};

// 查看博客详情
const handleView = (row: BlogListOutput) => {
	message.info(`查看博客: ${row.title}`);
	// 根据实际需求实现跳转到详情页逻辑
};

// 新增博客
const handleAdd = () => {
	currentBlogId.value = null;
	showEditModal.value = true;
};

// 编辑博客
const handleEdit = (row: BlogListOutput) => {
	currentBlogId.value = row.id;
	showEditModal.value = true;
};

// 保存博客 回调
const handleSaveBlog = () => {
	// 更新表格数据或重新获取数据
	fetchBlogList();
	// message.success('博客保存成功');
};

// 关闭编辑弹窗
const handleCloseEditModal = () => {
	currentBlogId.value = null;
};

/**
 * 发布博客
 */
const published = (row: BlogListOutput) => {
	if (row.id) {
		blogApi.Publication(row.id).then(() => {
			message.success('博客发布成功');
			fetchBlogList();
		})
	}
	else {
		message.error('请选择要发布的博客');
	}
}

/**
 * 删除博客
 */
const deleteBlog = (row: BlogListOutput) => {
	if (row.id) {
		blogApi.Delete(row.id).then(() => {
			message.success('博客删除成功');
			fetchBlogList();
		})
	}
	else {
		message.error('请选择要删除的博客');
	}
}

// 组件挂载时获取数据
onMounted(() => {
	fetchBlogList();
});
</script>

<style scoped>
.blog-list-container {
	padding: 16px;
}
</style>
